package cn.edkuir.search.service.impl;

import cn.edkuir.common.to.es.SkuEsModel;
import cn.edkuir.common.utils.Query;
import cn.edkuir.search.config.ElasticSearchConfig;
import cn.edkuir.search.constant.EsConstant;
import cn.edkuir.search.service.MallSearchService;
import cn.edkuir.search.vo.SearchParam;
import cn.edkuir.search.vo.SearchResult;
import com.alibaba.fastjson.JSON;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;


    /**
     * 在es中检索商品
     * @param searchParam 检索的所有参数
     * @return 检索结果
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = null;
        //1.动态构建出dsl语句
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        try {
            //2.执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

            //3.封装响应数据
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }


    //准备检索请求
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //构建dsl语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /*
            查询: 模糊匹配, 过滤(按照属性, 分类, 价格区间, 库存)
         */
        //1.bool query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must
        if(!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        //1.2 filter
        //三级分类
        if(searchParam.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }

        //品牌id
        if(!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }

        //属性 attrs=1_安卓:苹果&attrs=5_白色
        if(!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                //每一个属性都要构建一个filter
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();

                String[] s = attr.split("_");
                String attrId = s[0];   //检索的属性id
                String[] attrValue = s[1].split(":");  //检索的属性值
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));

                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQuery.filter(nestedQueryBuilder);
            }
        }

        //是否有库存
        if(searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }

        //价格区间 1_500/_500/500_
        if(!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            String price = searchParam.getSkuPrice();
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = price.split("_");
            if(s.length == 2) {
                //区间(大于小于)
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }else if(s.length == 1) {
                if(price.startsWith("_")) {
                    //小于
                    rangeQueryBuilder.lte(s[0]);
                }else if(price.endsWith("_")) {
                    //大于
                    rangeQueryBuilder.gte(s[0]);
                }
            }

            boolQuery.filter(rangeQueryBuilder);
        }

        //封装所有的查询条件
        searchSourceBuilder.query(boolQuery);


        /*
            排序, 分页, 高亮
         */
        //2.1 排序 sort=saleCount_asc/desc
        if(!StringUtils.isEmpty(searchParam.getSort())) {
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            searchSourceBuilder.sort(s[0], s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }

        //2.2 分页
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3 高亮
        if(!StringUtils.isEmpty(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");

            searchSourceBuilder.highlighter(highlightBuilder);
        }


        /*
            聚合分析
         */
        //3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        //品牌子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);


        //3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId");

        //分类子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);


        //3.3 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1));
        attr_agg.subAggregation(attr_id_agg);

        searchSourceBuilder.aggregation(attr_agg);


        System.out.println("构建的dsl语句: " + searchSourceBuilder.toString());

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }


    //封装检索结果
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult result = new SearchResult();

        //所有命中的记录
        SearchHits hits = response.getHits();
        SearchHit[] hitArr = hits.getHits();

        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        if(hitArr != null && hitArr.length > 0) {
            for(SearchHit hit :  hitArr) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                //判断是否有高亮信息
                if(!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModelList.add(skuEsModel);
            }
        }
        //1. 返回的所有查询到的商品
        result.setProducts(skuEsModelList);

        Aggregations aggregations = response.getAggregations();

        //2. 当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();

        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdBuckets = attrIdAgg.getBuckets();
        for (Terms.Bucket attrIdBucket : attrIdBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性id
            long attrId = attrIdBucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            //得到属性名字
            ParsedStringTerms attrNameAgg = attrIdBucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            //得到属性所有值
            ParsedStringTerms attrValueAgg = attrIdBucket.getAggregations().get("attr_value_agg");
            List<String> attrValue = new ArrayList<>();
            //每个属性可能有多个值
            List<? extends Terms.Bucket> attrValueBuckets = attrValueAgg.getBuckets();
            for (Terms.Bucket attrValueBucket : attrValueBuckets) {
                String value = attrValueBucket.getKeyAsString();
                attrValue.add(value);
            }
            attrVo.setAttrValue(attrValue);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);


        //3. 当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> brandBuckets = brandAgg.getBuckets();

        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            //得到品牌的名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            //得到品牌的图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);


        //4. 当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> catalogBuckets = catalogAgg.getBuckets();

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for(Terms.Bucket bucket : catalogBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String key = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(key));

            //得到分类名字
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            Terms.Bucket subBucket = catalogNameAgg.getBuckets().get(0);
            String catalogName = subBucket.getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //=======以上信息从聚合中拿===========

        //5. 分页信息-当前页码
        result.setPageNum(searchParam.getPageNum());

        //6. 分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        //7. 分页信息-总页码
        int num = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? ((int) total / EsConstant.PRODUCT_PAGESIZE)
                : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(num);

        List<Integer> pageNavs = new ArrayList<>();
        for(int i = 1; i <= num; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        return result;
    }
}
